<!-- 柱状图 https://echarts.apache.org/examples/zh/editor.html?c=bar-simple -->

<template>
  <div class="chart-container">
    <div ref="chart" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import resize from "./mixins/resize";
export default {
  name: "BarChart",
  mixins: [resize],
  props: {
    list: {
      type: Array,
      required: true,
    },
    chartId: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
  },
  mounted() {
    this.initChart();
  },
  watch: {
    list: {
      handler() {
        this.initChart();
      },
      deep: true,
    },
  },
  methods: {
    initChart() {
      // 初始化 echarts 实例 dark
      // var myChart = echarts.init(document.getElementById(this.chartId),  'dark');
      const chartDom = this.$refs.chart;
      const myChart = echarts.init(chartDom, "");

      // 将传递过来的数据转换为 echarts 需要的格式
      const categories = this.list.map((item) => item.name);
      const values = this.list.map((item) => item.total);
      // console.log(categories, values)
      // 绘制图表
      myChart.setOption({
        title: {
          text: this.title,
        },
        tooltip: {},
        xAxis: {
          type: "category",
          data: categories,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            type: "bar",
            data: values,
            showBackground: true,
            itemStyle: {
              // 修改柱子颜色为蓝色
              color: "#1890ff",
            },
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
          },
        ],
      });
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
